import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import Article from '../views/Article.vue'
import Operation from '../views/Operation.vue'
import Layout from '../views/Layout.vue'
import Statistic from '../views/IAA.vue'
import Campaign from '../views/Campaign.vue'
import Channel from '../views/Channel.vue'
import Login from '../views/Login.vue'
import Flow from '../views/Flow.vue'
import IAA from '../views/IAA.vue'
import CategorySetting from '../views/CategorySetting.vue'
import { useAuthStore } from '../store/auth'
import Choreography from '../views/Choreography.vue'
import MaterialRecognition from '../views/MaterialRecognition.vue'
import WebsiteManagement from '../views/WebsiteManagement/index.vue'
const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresGuest: true } // 标记为需要访客身份
  },
  {
    path: '/',
    component: Layout, // 使用布局组件
    redirect: '/article-manage', // 重定向到article
    meta: { requiresAuth: true }, // 标记为需要认证
    children: [
      { path: 'article-manage', name: 'Article', component: Article, meta: { keepAlive: true } },
      { path: 'category-setting', name: 'CategorySetting', component: CategorySetting },
      { path: 'operation', name: 'Operation', component: Operation, meta: { keepAlive: true } },
      { path: 'statistic', name: 'Statistic', component: Statistic },
      { path: 'campaign', name: 'Campaign', component: Campaign, meta: { keepAlive: true } },
      { path: 'channel', name: 'Channel', component: Channel, meta: { keepAlive: true } },
      { path: 'flow', name: 'Flow', component: Flow, meta: { keepAlive: true } },
      { path: 'iaa', name: 'IAA配置管理', component: IAA, meta: { keepAlive: true } },
      { path: 'choreography', name: 'Choreography', component: Choreography, meta: { keepAlive: true } },
      { path: 'material-recognition', name: 'MaterialRecognition', component: MaterialRecognition, meta: { keepAlive: true } },
      { path: 'website-management', name: 'WebsiteManagement', component: WebsiteManagement }
    ]
  }

]
const router = createRouter({
  history: createWebHistory('/article'),
  routes
})

// 添加路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  const isAuthenticated = authStore.isAuthenticated
  if (to.meta.requiresAuth && !isAuthenticated) {
    // 如果需要认证且未登录，重定向到登录页
    next({ name: 'Login', query: { redirect: to.fullPath } })
  } else if (to.meta.requiresGuest && isAuthenticated) {
    // 如果需要访客身份但已登录，重定向到首页
    next({ path: '/' })
  } else {
    // 否则正常导航
    next()
  }
})

export default router